#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h>
#include <fcntl.h>

using namespace std;

string path = "/dev/pts/5";
struct thread_data
{
    int _sockfd;
    struct sockaddr_in _server;
    string _ip;
};

void *send_message(void * temp)
{
    thread_data *td = (struct thread_data*)temp;
    string message;
    cout << "welcome " << td->_ip << endl;
    while (true)
    {
        cout << "please enter: ";
        getline(cin, message);
        sendto(td->_sockfd, message.c_str(), message.size(), 0, (const sockaddr *)&td->_server, sizeof(td->_server));
    }
    
}

void* recv_message(void* temp)
{
    // int fd = open(path.c_str(), O_WRONLY);
    // if (fd < 0)
    // {
    //     perror("open");
    // }

    // dup2(fd, 2);

    thread_data *td = (struct thread_data *)temp;
    char buff[1024];
    sockaddr_in rec;
    socklen_t len = sizeof(rec);
    while (true)
    {
        ssize_t s = recvfrom(td->_sockfd, buff, sizeof(buff) - 1, 0, (sockaddr *)&rec, &len);
        if (s > 0)
        {
            buff[s] = 0;
            cerr << buff << endl;
        }
    }

    //close(fd);
}

int main()
{
    thread_data td;
    uint16_t port = 8000;
    //string ip = "106.54.46.147";
    string ip = "106.54.46.147";
    sockaddr_in in;
    bzero(&in, sizeof(in));
    td._server.sin_family = AF_INET;
    td._server.sin_addr.s_addr = inet_addr(ip.c_str());
    td._ip = ip;
    td._server.sin_port = htons(port);
    td._sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td._sockfd < 0)
    {
        cout << "socket error" << endl;
    }

    //client 需要绑定，但不显示绑定，由os自由选择
    pthread_t tid_send;
    pthread_t tid_recv;
    pthread_create(&tid_send, nullptr, send_message, &td);
    pthread_create(&tid_recv, nullptr, recv_message, &td);  
    
    pthread_join(tid_send, nullptr);
    pthread_join(tid_recv, nullptr);

    close(td._sockfd);
}